//
//  ViewController2.swift
//  NetEaseBUFF
//
//  Created by QFX on 2023/10/27.
//

import UIKit
import SwiftyJSON

class ViewController2: UIViewController,UITableViewDataSource,UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2 + list.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return -1
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let section = indexPath.section
        switch section {
        case 0:
            return 169
        case 1:
            return 110
        default:
            let data = self.list[(section-2)]
            let type = data["type"].int
            if type == 1{
                return 100
            }else if type == 2{
                if let videos = data["videos"].array{
                    let content = data["content"].stringValue
                    let height = self.textHeightFromTextString(text: content, textWidth: KScreenWidth-30, fontSize: 16, isBold: false)
                    if height < 80 {
                        if height + 180 > 230{
                            return 360
                        }
                    }
                }
                return 310
            }
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let section = indexPath.section

        switch section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "bannerCell") as! bannerCell
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: "gameCell") as! gameCell
            return cell
        default:
            let data = self.list[(section-2)]
            let type = data["type"].int
            if type == 1{
                let cell = tableView.dequeueReusableCell(withIdentifier: "newsCell") as! newsCell
                
                let news = data["news"].dictionary
                if let cover_url = news?["cover_url"]?.stringValue{
                    cell.iconImageView.sd_setImage(with: URL.init(string: cover_url))
                }
                
                if let title = news?["title"]?.stringValue{
                    cell.titleLabel.text = title
                }
                
                if let publish_time = news?["publish_time"]?.int{
                    let value = NSString(format: "%ld" , publish_time)
                    cell.timeLabel.text = self.updateTimeToCurrennTime(timeStamp: value.doubleValue)
                }
                if let replies = news?["replies"]?.int{
                    cell.commentNumLabel.text = "\(replies)"
                }
                
                if let ups_num = news?["ups_num"]?.int{
                    cell.likeNumLabel.text = "\(ups_num)"
                }
 
                return cell
            } else if type == 2{
                let news = data["news"].dictionary

                let cell = tableView.dequeueReusableCell(withIdentifier: "newCell2") as! newCell2
                if let author = news?["author"]?.stringValue{
                    cell.nickNameLabel.text = author
                }
                if let content = news?["content"]?.stringValue{
                    let height = self.textHeightFromTextString(text: content, textWidth: KScreenWidth-30, fontSize: 16, isBold: false)
                    if height < 80{
                        cell.titleHeightConstraint.constant = height
                    }else{
                        cell.titleHeightConstraint.constant = 80
                    }
                    cell.contentLabel.text = content
                }
                
                if let replies = news?["replies"]?.int{
                    cell.commentNumLabel.text = "\(replies)"
                }
                
                if let ups_num = news?["ups_num"]?.int{
                    cell.likeNumLabel.text = "\(ups_num)"
                }
                
                if let forwards = news?["forwards"]?.int{
                    cell.shareNumLabel.text = "\(forwards)"
                }
                if let avatar = news?["avatar"]?.stringValue{
                    cell.headImageView.sd_setImage(with: URL.init(string: avatar))
                }
                
                if let pictures = news?["pictures"]?.array{
                    cell.playImageView.isHidden = true
                    cell.playTime.isHidden = true
                    if pictures.count == 1{
                        let pic = pictures[0]["image_url"].stringValue
                        cell.contentImageView1.sd_setImage(with: URL.init(string: pic))
                        cell.contentImageView1.isHidden = false
                        cell.contentImageView2.isHidden = true
                        cell.contentImageView3.isHidden = true
                        cell.picWidthConstranint.constant = 200
                        cell.picHeightConstraint.constant = 124
                    }
                    if pictures.count == 2{
                        let pic1 = pictures[0]["image_url"].stringValue
                        cell.contentImageView1.sd_setImage(with: URL.init(string: pic1))
                        
                        let pic2 = pictures[1]["image_url"].stringValue
                        cell.contentImageView2.sd_setImage(with: URL.init(string: pic2))
                        
                        cell.contentImageView1.isHidden = false
                        cell.contentImageView2.isHidden = false
                        cell.contentImageView3.isHidden = true
                        cell.picWidthConstranint.constant = 120
                        cell.picHeightConstraint.constant = 124
                    }
                    
                    if pictures.count == 3{
                        let pic1 = pictures[0]["image_url"].stringValue
                        cell.contentImageView1.sd_setImage(with: URL.init(string: pic1))
                        cell.picWidthConstranint.constant = 120
                        cell.picHeightConstraint.constant = 124
                        cell.contentImageView1.isHidden = false
                        cell.contentImageView2.isHidden = false
                        cell.contentImageView3.isHidden = false

                        let pic2 = pictures[1]["image_url"].stringValue
                        cell.contentImageView2.sd_setImage(with: URL.init(string: pic2))
                        
                        let pic3 = pictures[2]["image_url"].stringValue
                        cell.contentImageView3.sd_setImage(with: URL.init(string: pic3))
                    }
                }
                
                if let videos = news?["videos"]?.array{
                    cell.playImageView.isHidden = false
                    cell.playTime.isHidden = false
                    if videos.count == 1{
                        let video = videos[0]["icon_url"].stringValue
                        cell.contentImageView1.sd_setImage(with: URL.init(string: video))
                        let height = self.textHeightFromTextString(text: cell.contentLabel.text ?? "", textWidth: KScreenWidth-30, fontSize: 16, isBold: false)
                        if height < 80 {
                            if height + 180 > 230{
                                cell.picWidthConstranint.constant = KScreenWidth-30
                                cell.picHeightConstraint.constant = 150
                            }else{
                                cell.picWidthConstranint.constant = 120
                                cell.picHeightConstraint.constant = 180
                            }
                        }
                        
                        let time = videos[0]["duration"].stringValue
                        let s = NSString(format: "%@", time)
                        cell.playTime.text = self.stringFromTimeInterval(interval: s.doubleValue)

                        cell.contentImageView1.isHidden = false
                        cell.contentImageView2.isHidden = true
                        cell.contentImageView3.isHidden = true
                    }
                }
                if let publish_time = news?["publish_time"]?.int{
                    let value = NSString(format: "%ld" , publish_time)
                    cell.timeLabel.text = self.updateTimeToCurrennTime(timeStamp: value.doubleValue)
                }
                return cell
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
            return cell
        }
    }
    

    @IBOutlet weak var tableView: UITableView!
    var list:[JSON] = []
    
    func stringFromTimeInterval(interval:TimeInterval) -> String {

        let ti = NSInteger(interval)
        let seconds = ti % 60
        let minutes = (ti / 60) % 60
 
          return String(format: "%0.2d:%0.2d",minutes,seconds)
    }
    
    func textHeightFromTextString(text: String, textWidth: CGFloat, fontSize: CGFloat, isBold: Bool) -> CGFloat {
        var dict: NSDictionary = NSDictionary()
        if (isBold) {
            dict = NSDictionary(object: UIFont.boldSystemFont(ofSize: fontSize),forKey: NSAttributedString.Key.font as NSCopying)
        } else {
            dict = NSDictionary(object: UIFont.systemFont(ofSize: fontSize),forKey: NSAttributedString.Key.font as NSCopying)
        }
        
        let rect: CGRect = (text as NSString).boundingRect(with: CGSize(width: textWidth,height: CGFloat(MAXFLOAT)), options: [NSStringDrawingOptions.truncatesLastVisibleLine, NSStringDrawingOptions.usesFontLeading,NSStringDrawingOptions.usesLineFragmentOrigin],attributes: dict as? [NSAttributedString.Key : Any] ,context: nil)
        return rect.size.height
    }
    //MARK: -根据后台时间戳返回几分钟前，几小时前，几天前
      func updateTimeToCurrennTime(timeStamp: Double) -> String {
            //获取当前的时间戳
            let currentTime = Date().timeIntervalSince1970
            print(currentTime,   timeStamp, "sdsss")
            //时间戳为毫秒级要 ／ 1000， 秒就不用除1000，参数带没带000
            let timeSta:TimeInterval = TimeInterval(timeStamp)
            //时间差
            let reduceTime : TimeInterval = currentTime - timeSta
            //时间差小于60秒
            if reduceTime < 60 {
                return "刚刚"
            }
            //时间差大于一分钟小于60分钟内
            let mins = Int(reduceTime / 60)
            if mins < 60 {
                return "\(mins)分钟前"
            }
            let hours = Int(reduceTime / 3600)
            if hours < 24 {
                return "\(hours)小时前"
            }
            let days = Int(reduceTime / 3600 / 24)
            if days < 30 {
                return "\(days)天前"
            }
            //不满足上述条件---或者是未来日期-----直接返回日期
            let date = NSDate(timeIntervalSince1970: timeSta)
            let dfmatter = DateFormatter()
            //yyyy-MM-dd HH:mm:ss
            dfmatter.dateFormat="yyyy年MM月dd日 HH:mm:ss"
            return dfmatter.string(from: date as Date)
        }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.tableView.dataSource =  self
        self.tableView.delegate = self
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        self.tableView.register(UINib(nibName: "bannerCell", bundle: nil), forCellReuseIdentifier: "bannerCell")
        self.tableView.register(UINib(nibName: "gameCell", bundle: nil), forCellReuseIdentifier: "gameCell")
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.tableView.register(UINib(nibName: "newsCell", bundle: nil), forCellReuseIdentifier: "newsCell")
        self.tableView.register(UINib(nibName: "newCell2", bundle: nil), forCellReuseIdentifier: "newCell2")
        
        self.getData()
    }
    
    func getData(){
        if let path = Bundle.main.path(forResource:"v3", ofType: "json"){
            if let data = NSData(contentsOfFile: path) as? Data{
                if let json = try?JSONSerialization.jsonObject(with: data , options: .mutableContainers){
                    let parseJson = JSON(json)
                    if  let list = parseJson["data"]["items"].array{
                        for index in 0 ..< 21 {
                            let dict = list[index]
                            if let type = dict["type"].int {
                                if type != 5{
                                    self.list.append(dict)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
